//
//  QQTLoginViewController.m
//  Bottle
//
//  Created by apple on 11-11-12.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "QQTLoginViewController.h"

@interface QQTLoginViewController(private)
- (NSURL*)generateURL:(NSString*)baseURL params:(NSDictionary*)params;
@end

@implementation QQTLoginViewController

@synthesize loginView;

- (id)initWithURL: (NSString *) serverURL
           params: (NSMutableDictionary *) params
         delegate: (id <TencentLoginViewDelegate>) delegate
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        // Custom initialization
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 416)];
        [self.view addSubview:_webView];
        _webView.delegate = self;
        
        
        _serverURL = [serverURL retain];
        _params = [params retain];
        _delegate = delegate;
        
        _loadingURL = [[self generateURL:serverURL params:params] retain];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:_loadingURL];
        
        [_webView loadRequest:request];
        
        UINavigationBar *navigateBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        UINavigationItem *navigateItem = [[UINavigationItem alloc] initWithTitle:@"QQ登陆"];
        UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
        navigateItem.leftBarButtonItem = buttonItem;
        [navigateBar pushNavigationItem:navigateItem animated:NO];
        [self.view addSubview:navigateBar];
        [navigateBar release];
        [navigateItem release];
        [buttonItem release];
    }
    return self;
}

- (void)dealloc
{
    [_webView   release];
    _delegate = nil;
    [_serverURL release];
    [_params    release];
    [_loadingURL    release];
    [super  dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)cancel
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)dialogDidCancel:(NSURL *)url {
	if ([_delegate respondsToSelector:@selector(dialogDidNotCompleteWithUrl:)]) {
		[_delegate dialogDidNotCompleteWithUrl:url];
	}
	[self dismissModalViewControllerAnimated:YES];
}

- (NSString *) getStringFromUrl: (NSString*) url needle:(NSString *) needle {
	NSString * str = nil;
	NSRange start = [url rangeOfString:needle];
	if (start.location != NSNotFound) {
		NSRange end = [[url substringFromIndex:start.location+start.length] rangeOfString:@"&"];
		NSUInteger offset = start.location+start.length;
		str = end.location == NSNotFound
		? [url substringFromIndex:offset]
		: [url substringWithRange:NSMakeRange(offset, end.location)];
		str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	}
	
	return str;
}

- (NSURL*)generateURL:(NSString*)baseURL params:(NSDictionary*)params {
	if (params) {
		NSMutableArray* pairs = [NSMutableArray array];
		for (NSString* key in params.keyEnumerator) {
			NSString* value = [params objectForKey:key];
			NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(
																						  NULL, /* allocator */
																						  (CFStringRef)value,
																						  NULL, /* charactersToLeaveUnescaped */
																						  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
																						  kCFStringEncodingUTF8);
			
			[pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
			[escaped_value release];
		}
		
		NSString* query = [pairs componentsJoinedByString:@"&"];
		NSString* url = [NSString stringWithFormat:@"%@?%@", baseURL, query];
		return [NSURL URLWithString:url];
	} 
	else {
		return [NSURL URLWithString:baseURL];
	}
}

#pragma mark - web view delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
	NSURL* url = request.URL;
    //	NSLog([NSString stringWithFormat:@"absolute url : %@", [url absoluteURL]]);
	
	NSRange start = [[url absoluteString] rangeOfString:@"access_token="];
	if (start.location != NSNotFound)
	{
		NSString * token = [self getStringFromUrl:[url absoluteString] needle:@"access_token="];
		NSString * expireTime = [self getStringFromUrl:[url absoluteString] needle:@"expires_in="];
		NSDate *expirationDate =nil;
		
		if (expireTime != nil) {
			int expVal = [expireTime intValue];
			if (expVal == 0) {
				expirationDate = [NSDate distantFuture];
			} else {
				expirationDate = [NSDate dateWithTimeIntervalSinceNow:expVal];
			} 
		} 
		
		if ((token == (NSString *) [NSNull null]) || (token.length == 0)) {
			[self dialogDidCancel:url];
			if ([_delegate respondsToSelector:@selector(tencentDialogNotLogin:)]) {
				[_delegate tencentDialogNotLogin:NO];
			}
		} else {
			if ([_delegate respondsToSelector:@selector(tencentDialogLogin:expirationDate:)]) {
				[_delegate tencentDialogLogin:token expirationDate:expirationDate];
			}
		}
		return NO;
	}
	else
	{
		return YES;
	}
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	// 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
	if (!([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102)) {
		[self dismissModalViewControllerAnimated:YES];
	}
}


@end
